package com.emm.yixun.website.service.call;

import java.io.IOException;    
import java.io.InputStream;    
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;    
import org.apache.poi.ss.usermodel.Sheet;    
import org.apache.poi.ss.usermodel.Workbook;    
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.CallCustomer;
import com.emm.yixun.common.model.CallCustomerInfo;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CallCustomerDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DistributionDto;
import com.emm.yixun.common.model.dto.FollowDto;
import com.emm.yixun.common.model.dto.ImportErrorDto;
import com.emm.yixun.common.model.dto.ImportStatisticsDto;
import com.emm.yixun.common.model.dto.TelRecordDto;
import com.emm.yixun.common.model.enums.CustomerOriginEnum;
import com.emm.yixun.common.model.enums.FollowModeEnum;
import com.emm.yixun.common.model.enums.FollowTypeEnum;
import com.emm.yixun.common.model.enums.IsReadEnum;
import com.emm.yixun.common.model.enums.ProcessStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CallCustomerServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.DistributionServiceFacade;
import com.emm.yixun.customer.service.FollowServiceFacade;
import com.emm.yixun.customer.service.ImportErrorServiceFacade;
import com.emm.yixun.customer.service.ImportStatisticsServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.website.common.utils.PatternUtil;
import com.emm.yixun.website.common.utils.security.ShiroUtil;

/**
 * call客导入
 * 
 * @author jzliu
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class CallCustomerServiceImp implements CallCustomerService{
	
	protected Logger logger = LoggerFactory.getLogger(CallCustomerServiceImp.class);
	
	@Autowired
	private ImportStatisticsServiceFacade importStatisticsServiceFacade;
	@Autowired
	private CallCustomerServiceFacade callCustomerServiceFacade;
	@Autowired
	private ImportErrorServiceFacade importErrorServiceFacade;
	@Autowired 
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private DistributionServiceFacade distributionServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private FollowServiceFacade followServiceFacade;
	
	
	@Transactional
	@Override
	public Response<ImportStatisticsDto> uploadExcel(String title, InputStream file, String fileType){
		Response<ImportStatisticsDto> res = new Response<ImportStatisticsDto>();
		DecimalFormat df = new DecimalFormat("0.##");
		User user=ShiroUtil.getCurrentUser(); //获取登录用户信息
		//读取excel
		Map<String, List<CallCustomerDto>> map= read(file, fileType);
		//保存正确的数据
    	List<CallCustomerDto> list = map.get("success");
    	//保存问题数据
    	List<CallCustomerDto> failList = map.get("fail");
    	//当正确数据与错误数据全部为空的时候 ，提示导入错误
    	if(list.size() < 0 && failList.size() < 0 ){
    		res.fail("9999", "excel导入错误");
    		return res;
    	}
    	logger.debug("excel导入成功Success，准备插入数据库");
    	//查询电话号码重复的数据
    	int phoneSize = 0;
		List<CallCustomer> phoneList = phone(list);
		if(phoneList != null){
			phoneSize = phoneList.size();
		}
		
    	int successCount = list.size() - phoneSize; //成功条数
    	int failCount = failList.size() + phoneSize; //失败条数
    	int total = successCount+failCount; //总条数
    	logger.debug("失败条数==="+failCount+"; 成功条数==="+successCount+"; 总条数==="+total);
    	double ratio = Double.parseDouble(successCount+"")/Double.parseDouble(total+"") * 100;
    	ImportStatisticsDto entity = new ImportStatisticsDto();
    	entity.setTitle(title); //标题
    	entity.setTotal(successCount+failCount); 
    	entity.setSuccessCount(successCount); 
    	entity.setFailCount(failCount); 
    	entity.setSuccessRatio(new BigDecimal(df.format(ratio)));
    	entity.setMerchantId(user.getMerchantId()); //商户ID
    	entity.setCreateUserId(user.getId()); //导入人ID
    	entity.setDelFlag("0");
    	Response<ImportStatisticsDto> resDto = importStatisticsServiceFacade.save(entity);
    	logger.debug("cave importStatistics==="+resDto.isSuccess());
    	if(resDto.isSuccess()){
    		ImportStatisticsDto dto = resDto.getEntity();
    		//导入成功数据
    		for(int i = 0; i < list.size(); i++){
    			CallCustomerDto callDto = (CallCustomerDto)list.get(i);
    			
    			//过滤重复电话号码
    			boolean flag = true;
    			for(int p = 0; p < phoneSize; p++){
    				CallCustomer phone = (CallCustomer)phoneList.get(p);
    				if(phone.getPhone().equals(callDto.getPhone())){
    					//当有重复时号码时，跳出循环
    					flag = false;
    					callDto.setRemark("电话号码重复");
    					failList.add(callDto);
    					break;
    				}
    			}
    			
    			if(flag){
    				callDto.setStatus("0"); //待分配
        			callDto.setImpId(dto.getId()); //统计表ID
        			callDto.setMerchantId(user.getMerchantId()); //商户ID
        			callDto.setCreateUserId(user.getId()); //导入人ID
        			callDto.setCallNum("0"); //沟通次数 ，默认0次
        			callDto.setDelFlag("0");
        			callCustomerServiceFacade.save(callDto);
    			}
    		}
    		logger.debug("导入失败信息==="+failList.size());
    		//导入失败数据
    		for(int i = 0; i < failList.size(); i++){
    			CallCustomerDto callDto = (CallCustomerDto)failList.get(i); //获取错误数据
    			ImportErrorDto errorDto = new ImportErrorDto();
    			errorDto.setUserName(callDto.getUserName()); //客户名称
    			errorDto.setPhone(callDto.getPhone());	//客户电话
    			errorDto.setRemark(callDto.getCaption()); //说明
    			errorDto.setFailure(callDto.getRemark()); //出错信息
    			errorDto.setImpId(dto.getId());	//统计表ID
    			errorDto.setMerchantId(user.getMerchantId()); //商户ID
    			errorDto.setCreateUserId(user.getId()); //导入人ID
    			errorDto.setDelFlag("0");
    			importErrorServiceFacade.save(errorDto);
    		}
    		logger.debug("导入成功===Success");
    	}
    	
		return resDto;
	}
	
    public Map<String, List<CallCustomerDto>> read(InputStream file, String fileType) {    
    	Map<String, List<CallCustomerDto>> map = new HashMap<String, List<CallCustomerDto>>();
    	
    	//保存正确的数据
    	List<CallCustomerDto> list = new ArrayList<CallCustomerDto>();
    	//保存问题数据
    	List<CallCustomerDto> failList = new ArrayList<CallCustomerDto>();
    	
        try {
			Workbook wb = null;
			if (fileType.equals("xls")) {
				wb = new HSSFWorkbook(file);
			} else if (fileType.equals("xlsx")) {
				wb = new XSSFWorkbook(file);
			} else {
				logger.debug("您上传的excel格式不正确");
			}
			Sheet sheet1 = wb.getSheetAt(0);
			logger.debug("excel上传行数===="+sheet1.getLastRowNum());
			Map<String, String> phoneMap = new HashMap<String, String>(); //用于判断excel中的号码是否重复
			for (int i = 1; i <= sheet1.getLastRowNum(); i++) {
				Row row = sheet1.getRow(i);
				CallCustomerDto dto = new CallCustomerDto();
				String failMsg = "";
				//客户姓名
				if (row.getCell(0) != null) {
					dto.setUserName(row.getCell(0).toString());
				} 
//				else {
//					failMsg = "姓名不能为空；";
//				}
				//手机号
				if (row.getCell(1) != null) {
					Cell cell = row.getCell(1);
					cell.setCellType(Cell.CELL_TYPE_STRING);
					String phone = cell.getStringCellValue();
					System.out.println("===="+phoneMap.get(phone));
					if(StringUtils.isNotBlank(phoneMap.get(phone))){
						failMsg += "电话号码重复；";
					}else{
						if (!PatternUtil.isMobile(phone)
								&& !PatternUtil.isPhone(phone)) {
							failMsg += "电话号码格式错误；";
						}
					}
					dto.setPhone(phone);
					phoneMap.put(phone, phone);
				} else {
					failMsg += "电话号码不能为空;";
				}
				//说明
				if (row.getCell(2) != null) {
					dto.setCaption(row.getCell(2).toString());
				}

				if (!"".equals(failMsg)) {
					logger.debug("excel错误信息==="+failMsg);
					dto.setRemark(failMsg);
					failList.add(dto);
				} else {
					list.add(dto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        map.put("success", list);
        map.put("fail", failList);
        return map;
    }  
    
    //查询电话号码是否有重复
    public List<CallCustomer> phone(List<CallCustomerDto> dtoList){
    	List<CallCustomer> list = new ArrayList<CallCustomer>();
    	String sql = "";
    	for(int i = 0; i < dtoList.size(); i++){
    		CallCustomerDto dto = (CallCustomerDto)dtoList.get(i);
    		sql += dto.getPhone() + "' or phone = '";
    	}
    	if(!"".equals(sql)){
    		sql = " phone = '" + sql.substring(0, sql.length()-13);
    	}
    	CallCustomerDto dto = new CallCustomerDto();
    	dto.setPhone(sql);
    	logger.debug("查询电话号码是否重复的条件===="+sql);
    	ResponseList<CallCustomer> res = callCustomerServiceFacade.distinctPhone(dto);
    	if(res.isSuccess()){
    		list = res.getEntity();
    	}
    	return list;
    }
    
    @Transactional
	@Override
    public Response<CustomerDto> addCustomer(CallCustomerDto dto, String projectId, List<TelRecordDto> telList){
    	Response<CustomerDto> resCus = new Response<CustomerDto>();
    	
    	//查询项目信息
    	Response<Project> response = projectServiceFacade.findById(Long.parseLong(projectId));
		Project project = response.getEntity();
    	
    	CustomerDto cusDto = new CustomerDto();
    	cusDto.setCustomerPhone(dto.getPhone());
		cusDto.setMerchantId(project.getMerchantId());
		cusDto.setProjectId(project.getId());
		cusDto.setDelFlag("0");
		//查询是否已存在
		ResponseList<Customer> resList = customerServiceFacade.findByDto(cusDto);
		if(resList.isSuccess()){
			if(resList.getEntity() != null){
				resCus.setSuccess(false);
				resCus.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
				resCus.setResultMessage("客户已存在");
				return resCus;
			}
		}
    	
    	cusDto.setCustomerName(dto.getUserName());
		cusDto.setProjectId(project.getId());
		cusDto.setProjectCode(project.getProjectCode());
		cusDto.setUserCode(project.getUserCode());
		cusDto.setAccessCode(project.getAccessCode());
		cusDto.setCustomerOrigin(CustomerOriginEnum.CALLKE_11.getNo());
		cusDto.setCreateUserId(dto.getUpdateUserId());
		resCus = customerServiceFacade.save(cusDto);
		if(!resCus.isSuccess()){
			resCus.setSuccess(false);
			resCus.setErrorCode("9999");
			resCus.setResultMessage("转客失败");
			return resCus;
		}
//		//保存客户记录表
//		CustomerDto customer = resCus.getEntity();
//		DistributionDto disDto = new DistributionDto();
//		disDto.setCustomerId(customer.getId());
//		disDto.setProjectId(customer.getId());
//		disDto.setProjectCode(customer.getProjectCode());
//		disDto.setUserCode(customer.getUserCode());
//		disDto.setAccessCode(customer.getAccessCode());
//		disDto.setMerchantId(customer.getMerchantId());
//		disDto.setDistributionTime(DateUtils.getCurrentTS());
//		disDto.setIsValid("1"); //有效
//		disDto.setCreateUserId(customer.getCreateUserId());
//		disDto.setProcessStatus(ProcessStatusEnum.NO.getNo());
//		disDto.setDelFlag("0");
//		Response<DistributionDto> resDis = distributionServiceFacade.save(disDto);
//		
//		//跟进内容
//		StringBuffer content = new StringBuffer();
//		content.append("关注问题：" + dto.getConcern());		
//		content.append("<br/>备注：" + dto.getRemark());
//		content.append("<br/>到访时间： " + DateUtils.DateToString(dto.getVisitTime(), DateStyle.YYYY_MM_DD));
//		
//		//保存跟进总记录
//		FollowDto fd = new FollowDto();
//	 	fd.setMerchantId(customer.getMerchantId());
//	 	fd.setUserCode(customer.getUserCode());
//	 	fd.setCreateUserId(customer.getId());
//	 	fd.setCustomerId(customer.getId());
//	 	fd.setProjectId(customer.getProjectId());
//	 	fd.setProjectCode(customer.getProjectCode());
//	 	fd.setAccessCode(customer.getProjectCode());
//	 	fd.setDelFlag("0");
//		fd.setFollowContent(content.toString());
//		fd.setFollowType(FollowTypeEnum.TEXT.getNo());
//		fd.setFollowTime(customer.getCreateTime());
//		fd.setFollowMode(FollowModeEnum.GOCALL.getNo());
//		fd.setUpdateTime(customer.getCreateTime());
//		fd.setIsRead(IsReadEnum.UNREAD.getNo());
//		fd.setIsSend("0");
//	 	Response<FollowDto> res = followServiceFacade.save(fd);
//		
//		//保存跟进明细记录
//		for(int i = 0; i < telList.size(); i++){
//			TelRecordDto telDto = (TelRecordDto)telList.get(i);
//			fd.setTelRecordId(telDto.getId());
//			fd.setDelFlag("0");
//			fd.setFollowContent("拨打电话自动生成跟进");
//			fd.setFollowType(FollowTypeEnum.VOICE.getNo());
//			fd.setFollowTime(telDto.getCreateTime());
//			fd.setFollowMode(FollowModeEnum.GOCALL.getNo());
//			fd.setUpdateTime(telDto.getCreateTime());
//			fd.setIsRead(IsReadEnum.UNREAD.getNo());
//			fd.setIsSend("0");
//			Response<FollowDto> resFollow = followServiceFacade.save(fd);
//		}
		
    	return resCus;
    }
}
